package com.biz.impl;

import com.alibaba.fastjson.JSONObject;
import com.biz.*;
import com.core.BizException;
import com.entity.bo.MinaLoginFormBO;
import com.entity.model.Customer;
import com.util.AES;
import com.util.HttpRequest;
import com.util.LoginTicketUtil;
import com.util.SystemConstant;
import com.wechat.mina.ComponentUtil;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Condition;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Administrator on 2017-09-05.
 */
@Service
@Transactional
public class WechatMinaBizImpl implements WechatMinaBiz {
    @Autowired
    private CustomerBiz customerBiz;

    @Override
    public Map login(MinaLoginFormBO model) {
        String url = "https://api.weixin.qq.com/sns/jscode2session";
        Map<String, String> maps = new HashMap<>();
        maps.put("appid", "wxe4d766ec89b115c0");
        maps.put("secret", "20f627109cd98f44b1d6c77c87c316fe");
        maps.put("js_code", model.getCode());
        maps.put("grant_type", "authorization_code");
        //调用微信接口获取openId用户唯一标识
        JSONObject wxReturnValue = JSONObject.parseObject(HttpRequest.sendGet(url, maps));

        String openid = wxReturnValue.getString("openid");
        if (StringUtils.isBlank(openid)) {
            throw new BizException("数据异常请重试");
        }
        Customer customer = null;
        HashMap map = new HashMap();
        //判断当前平台是否有注册过
        map.put("openid", openid);
        customer = customerBiz.getByConnect(map);
        HashMap rep = new HashMap();
        rep.put("openid", openid);
        if (customer != null) {

        } else {
            customer = new Customer();
            customer.setNickName(model.getNickName());
            customer.setUserName(model.getNickName());
            customer.setOpenid(openid);
            customer.setHeadImgUrl(model.getAvatarUrl());
            Integer gender = model.getGender();
            if (null != gender) {
                customer.setSex(String.valueOf(gender));
            }
            customer.setProvinceCode(model.getProvince());
            customer.setCityCode(model.getCity());
            customer.setIsVip(0);
            customerBiz.save(customer);
        }

        rep.put("customerId", customer.getId());
        rep.put("isVip", customer.getIsVip());
        rep.put("idCard", customer.getIdCard());
        rep.put("trueName", customer.getTrueName());
        rep.put(SystemConstant.LOGIN_TICKET, LoginTicketUtil.getTicket(customer.getId()));
        rep.put("hasPhone", StringUtils.isNotBlank(customer.getAccount()) ? true : false);
        rep.put("headImgUrl", customer.getHeadImgUrl());
        //rep.put("vipStartDate", customer.getVipStartDate());
        rep.put("nickName", customer.getNickName());
        rep.put("userName", customer.getNickName());
        long day = 0;
        if (customer.getIsVip() > 0) {
            if (customer.getIsVip() == 1) {
                long diff = customer.getVipEndDate().getTime() - new Date().getTime();
                day = diff / (1000 * 24 * 60 * 60);
            }

        }

        rep.put("days", day);
        return rep;
    }


    @Override
    public JSONObject decodeInfo(Integer customerId, String encryptedData, String iv) {
        Customer customer = customerBiz.findById(customerId);
        String sessionKey = "";
        if (sessionKey == null || StringUtils.isBlank(encryptedData) || StringUtils.isBlank(iv)) {
            return null;
        }
        try {
            String result = decodeData(sessionKey, encryptedData, iv);
            return JSONObject.parseObject(result);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private String decodeData(String sessionKey, String encryptedData, String iv) throws Exception {
        byte[] result = AES.decrypt(Base64.decodeBase64(encryptedData), Base64.decodeBase64(sessionKey), Base64.decodeBase64(iv));
        return new String(result, "utf-8");
    }
}
